import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Book } from './entities/book.entity';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';

@Injectable()
export class BookService {
  constructor(
    @InjectRepository(Book)
    private bookRepository: Repository<Book>,
  ) {}

  async create(createBookDto: CreateBookDto): Promise<Book> {
    // 检查ISBN是否已存在
    const existingBook = await this.bookRepository.findOne({
      where: { isbn: createBookDto.isbn },
    });

    if (existingBook) {
      throw new ConflictException(`ISBN为${createBookDto.isbn}的图书已存在`);
    }

    const book = this.bookRepository.create(createBookDto);
    return this.bookRepository.save(book);
  }

  async findAll(): Promise<Book[]> {
    return this.bookRepository.find();
  }

  async findOne(id: string): Promise<Book> {
    const book = await this.bookRepository.findOne({ where: { id } });
    if (!book) {
      throw new NotFoundException(`ID为${id}的图书不存在`);
    }
    return book;
  }

  async update(id: string, updateBookDto: UpdateBookDto): Promise<Book> {
    const book = await this.findOne(id);

    // 如果更新ISBN，检查新ISBN是否已被其他图书使用
    if (updateBookDto.isbn && updateBookDto.isbn !== book.isbn) {
      const existingBook = await this.bookRepository.findOne({
        where: { isbn: updateBookDto.isbn },
      });

      if (existingBook) {
        throw new ConflictException(`ISBN为${updateBookDto.isbn}的图书已存在`);
      }
    }

    // 更新图书信息
    Object.assign(book, updateBookDto);
    return this.bookRepository.save(book);
  }

  async remove(id: string): Promise<void> {
    const book = await this.findOne(id);
    await this.bookRepository.remove(book);
  }

  // 添加示例数据
  async addSampleBooks(): Promise<Book[]> {
    const sampleBooks = [
      {
        title: 'TypeScript编程实战',
        author: '李四',
        publisher: '电子工业出版社',
        publishDate: new Date('2022-05-15'),
        isbn: '978-7-121-12345-6',
        price: 79.00,
        stock: 50,
        description: 'TypeScript从入门到精通的实战指南',
      },
      {
        title: 'NestJS权威指南',
        author: '王五',
        publisher: '人民邮电出版社',
        publishDate: new Date('2023-01-10'),
        isbn: '978-7-115-67890-1',
        price: 89.00,
        stock: 30,
        description: '全面讲解NestJS框架的开发实践',
      },
      {
        title: '深入浅出Node.js',
        author: '张三',
        publisher: '清华大学出版社',
        publishDate: new Date('2021-08-20'),
        isbn: '978-7-302-54321-9',
        price: 69.00,
        stock: 40,
        description: 'Node.js核心原理与最佳实践',
      },
    ];

    const books: Book[] = [];
    
    for (const bookData of sampleBooks) {
      // 检查ISBN是否已存在
      const existingBook = await this.bookRepository.findOne({
        where: { isbn: bookData.isbn },
      });

      if (!existingBook) {
        const book = this.bookRepository.create(bookData);
        books.push(await this.bookRepository.save(book));
      }
    }

    return books;
  }
}
